#!/usr/bin/env python
# encoding: utf-8

import sys
import logging
import os

from time import sleep
from http.server import TornadoServer
from termcolor import colored
from config import init_config, config
from worker.syncRule import syncRule
from worker.explainAlertMesg import alert_consumer

reload(sys)
sys.setdefaultencoding("utf-8")


logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d]: [module: %(module)s, func: %(funcName)s]: '
                           '%(levelname)s -> %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='logs/Main.log',
                    filemode='ab+')

log = logging.getLogger("")


class Main(object):
    def __init__(self):
        print colored(u"start process..", "yellow")

    def process(self):
        log.info("excute init config")
        pid = os.fork()

        if not pid:
            # 监听任务队列
            syncRule()
            alert_consumer()
            TornadoServer.run()
        while True:  # blocking..
            try:
                pid, _ = os.wait()
            except OSError as e:
                return False
            except KeyboardInterrupt:
                sleep(0.5)
                print colored('Kill {0}'.format(pid), "red")
                self.close()
                return True

    def close(self):
        import os
        os._exit(0)


if __name__ == "__main__":
    Main().process()